package com.partsoft.dits.message;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

/**
 * 基本的消息级联接口实现对象
 * TODO 谁来实现序列化
 */
@SuppressWarnings({"unchecked"})
public class BaseMessageConcatenation implements MessageConcatenation, Cloneable {

	private static final long serialVersionUID = -3635051871454869814L;

	private List<MessageEntity> parents = Collections.EMPTY_LIST;
	
	private List<MessageEntity> childs = Collections.EMPTY_LIST;
	
	public BaseMessageConcatenation() {}
	
	public boolean hasParents() {
		return !CollectionUtils.isEmpty(parents);
	}

	public MessageEntity[] getParents() {
		return parents.toArray(new MessageEntity[0]);
	}

	public boolean hasChilds() {
		return !CollectionUtils.isEmpty(childs);
	}

	public MessageEntity[] getChilds() {
		return childs.toArray(new MessageEntity[0]);
	}
	
	/**
	 * 获得真实的上级列表，对返回值进行操作就是对实际数据进行操作。
	 */
	protected List<MessageEntity> getRawChilds() {
		if (childs == Collections.EMPTY_LIST) childs = new LinkedList<MessageEntity>();
		return childs;
	}
	
	/**
	 * 获得真实的下级列表，对返回值进行操作就是对实际数据进行操作。
	 */
	protected List<MessageEntity> getRawParents() {
		if (parents == Collections.EMPTY_LIST) parents = new LinkedList<MessageEntity>();
		return parents;
	}
	
	public boolean addParent(MessageEntity parent) {
		Assert.notNull(parent);
		return getRawParents().add(parent);
	}
	
	public boolean addParents(MessageEntity []parents) {
		if (ObjectUtils.isEmpty(parents)) return false;
		return addParents(Arrays.asList(parents));
	}
	
	public boolean addParents(Collection<? extends MessageEntity>parents) {
		if (CollectionUtils.isEmpty(parents)) return false;
		return getRawParents().addAll(parents);
	}
	
	public boolean addChild(MessageEntity child) {
		Assert.notNull(child);
		return getRawChilds().add(child);
	}
	
	public boolean addChilds(MessageEntity []childs) {
		if (ObjectUtils.isEmpty(childs)) return false;
		return addChilds(Arrays.asList(childs));
	}
	
	public boolean addChilds(Collection<? extends MessageEntity>childs) {
		if (CollectionUtils.isEmpty(childs)) return false;
		return getRawChilds().addAll(childs);
	}
	
	@Override
	public BaseMessageConcatenation clone() {
		BaseMessageConcatenation ac = null;
		try {
			ac = (BaseMessageConcatenation) super.clone();
		} catch (Throwable e) {
			throw new IllegalStateException(e);
		}
		if (!ac.hasChilds()) 
			ac.childs = Collections.EMPTY_LIST;
		else
			ac.childs = new LinkedList<MessageEntity>(Arrays.asList(ac.getChilds()));
		if (!ac.hasParents()) 
			ac.parents = Collections.EMPTY_LIST;
		else
			ac.parents = new LinkedList<MessageEntity>(Arrays.asList(ac.getParents()));
		return ac;
	}

}
